package com.fanrui.code.chess.mahjong;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

import org.apache.commons.lang3.RandomUtils;

import com.fanrui.code.chess.mahjong.MahjongRules.CurrencyType;
import com.fanrui.code.chess.mahjong.round.MahjongOperationResponse;
import com.fanrui.code.mahjong.util.MahjongCardUtil;
import com.fanrui.proto.cmd.Operation;

public class MahjongRobot extends CanHostingGamer {

	public final static int cheatRate = 60;

	public MahjongRobot(int id, long robotId, int tableId) {
		super(id, robotId, tableId, "0.0.0.0", 0, 0);
		waitTime = new AtomicInteger(RandomUtils.nextInt(1, 5));
	}

	@Override
	public void notifyResponse(MahjongOperationResponse response, int waitTime) {
		if (response.getType() == Operation.TOUCH && response.getOperationId() != getPlayerID()) {
			return;
		}
		currendResponse = response;
		List<Mahjong> cards = MahjongCardUtil.getInstance().clone(getHandCards());

		if (response.getType() == Operation.SEND) {
			cards.add(response.getCard());
		}
		if (executeDefaultNum < 13) {
			waitTime = RandomUtils.nextInt(1, 2);
		} else if (executeDefaultNum % 5 == 0) {
			waitTime = RandomUtils.nextInt(2, 6);
		} else {
			waitTime = RandomUtils.nextInt(1, 3);
		}

		if (waitTime > 0) {
			if (this.waitTime == null) {
				this.waitTime = new AtomicInteger(waitTime);
			} else {
				this.waitTime.set(waitTime);
			}
		}
	}

	@Override
	public boolean checkReady() {
		if (!isReady() && !getAFK() && !getLeave()) {
			return true;
		} else {
			return false;
		}
	}

	public int getCurrentyIncome() {
		AbstractMahjongTable<?> table = getTable();
		if (table.getGameRules().getCurrencyType() == CurrencyType.Gold) {
			return (int) (playerInfo.getGold() - getIncome());
		} else {
			return (int)  getIncome();
		}
	}

	@Override
	public void reset() {
		super.reset();
		if (waitTime != null) {
			waitTime.set(5);
		} else {
			waitTime = new AtomicInteger(5);
		}

	}
	
	public void changeCardSort(List<Mahjong> cardHeap) {
		List<Mahjong> huCards = MahjongCardUtil.getInstance().getHuCards(handCards, null);
		Integer replaceCardIndex = null;
		if (huCards != null && !huCards.isEmpty()) {// 如果可以胡牌找出一张可以胡的牌
			loop: for (Mahjong mahjong : huCards) {
				for (int i = 0; i < cardHeap.size(); i++) {
					if (mahjong.cardEquals(cardHeap.get(i))) {
						replaceCardIndex = i;
						break loop;
					}
				}
			}
		}

		Collections.swap(cardHeap, 0, replaceCardIndex);
	}
}
